# -*- coding: utf-8 -*-

######################################################
## sabNzbd - Version (v1.51)                        ##
######################################################
##
## - Minor change to Pct reported when too small.
##
##
import  traceback,string,os
from    xbmcgui     import ListItem as xListItem
from    types       import *
from    time        import time     as tTime
from    re          import findall  as reFindall, compile as reCompile, DOTALL as reDotAll, search as reSearch, sub as reSub
from    urllib      import quote    as UrlQuote
import  core

class Controller:
    def __init__(self,win,PathName):
        self.win                    =   win
        self._                      =   self.win._
        self.ClearVars()
        self.Version                =   '1.50'
        self.Dir                    =   'Sabnzbd'
        self.Title                  =   'SabNzbd'
        self.FileType               =   'nzb'
        self.win.Title              =   self.Title
        self.PAUSED                 =   False

        ## Sabnzbd Network Info
        self.TIMEOUT                =   int(10.0)
        self.FILEHASH               =   ''
        self.IP                     =   '192.168.0.1'
        self.PORT                   =   '8080'
        self.USER                   =   ''
        self.PASS                   =   ''
        self.DEFOPTION              =   '3'
        self.LoginType              =   'HTML'

        self.URL                    =   'http://%s/sabnzbd/'

        ## New Labels to Toggle Through..
        self.DNLABEL_               =   ['Size'     ,   'Left' ,    'Eta'      ,    'Time' ,    'CompPct']
        self.UPLABEL_               =   ['Date']

        self.KeyMenus               =   {'150': {'A':('Select/Action','','torrentmenu')             ,   \
                                                 'B':('Move Down','','moveDown')                    ,   \
                                                 'X':('Display Files','','showfiles')               ,   \
                                                 'Y':('Move Up','','moveUp')}                       ,   \
                                         '250': {'X':('Purge History' ,'','purgehistory')}          ,   \
                                         '450': {'X':('Back to NZB View','','shownzbs' )}           ,   \
                                         '16':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('Sabnzbd COnfig','','configmenu')             ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '17':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('Sabnzbd COnfig','','configmenu')             ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '26':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('Sabnzbd COnfig','','configmenu')             ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '27':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('Sabnzbd COnfig','','configmenu')             ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '46':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('Sabnzbd COnfig','','configmenu')             ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '47':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('Sabnzbd COnfig','','configmenu')             ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '0':   {'A':('Select/Action','','')}}
        

        ## Check against Read config data.
        if not (self.win.Config.has_key(self.Title))                :
            self.win.Config[self.Title]               = {}
        if not (self.win.Config[self.Title].has_key('IP'))          :
            self.win.Config[self.Title]['IP']         = self.IP
        if not (self.win.Config[self.Title].has_key('PORT'))        :
            self.win.Config[self.Title]['PORT']       = self.PORT
        if not (self.win.Config[self.Title].has_key('USER'))        :
            self.win.Config[self.Title]['USER']       = self.USER
        if not (self.win.Config[self.Title].has_key('PASS'))        :
            self.win.Config[self.Title]['PASS']       = self.PASS
        if not (self.win.Config[self.Title].has_key('TIMEOUT'))     :
            self.win.Config[self.Title]['TIMEOUT']    = self.TIMEOUT
        if not (self.win.Config[self.Title].has_key('DEFOPTION'))   :
            self.win.Config[self.Title]['DEFOPTION']  = self.DEFOPTION
        if not (self.win.Config[self.Title].has_key('DNLABEL_'))   :
            self.win.Config[self.Title]['DNLABEL_']   = self.DNLABEL_[0]
        if not (self.win.Config[self.Title].has_key('UPLABEL_'))   :
            self.win.Config[self.Title]['UPLABEL_']   = self.UPLABEL_[0]
        
        
        ### Pass these Parameters Back for Ease ###
        if not self.win.Modules.has_key('Ctrl')             :   self.win.Modules['Ctrl']    =   {} 
        self.win.Modules['Ctrl'][self.Title]                =   {}
        self.win.Modules['Ctrl'][self.Title]['Path']        =   PathName
        self.win.Modules['Ctrl'][self.Title]['FileType']    =   self.FileType

        ## Update all relevant Parameters ##
        self.UpdateAll()

####################################################################################################################
######## START ###################### COMMUNICATION ################################################################      
####################################################################################################################

    def UpdateAll(self)     :
        ## Update the Variables
        self.UpdateUrl()
        self.UpdateLogin()
        self.UpdateOption()
        self.UpdateTimeout(self.TIMEOUT)


    def ClearVars(self):
        self.Comms                  =   {}

        
    def UpdateUrl(self) :
        self.FullUrl                =   self.URL    %  \
                                        str(self.win.Config[self.Title]['IP'] +':'+ self.win.Config[self.Title]['PORT'])
        
    def UpdateLogin(self) :
        try :
            self.Login = ''
            if self.win.Config[self.Title].has_key('USER') and self.win.Config[self.Title].has_key('PASS')  :
                if self.win.Config[self.Title]['USER'] != '' and self.win.Config[self.Title]['PASS'] != ''  :
                    self.Login = 'ma_username='+ str(self.win.Config[self.Title]['USER']) +'&'+ \
                                 'ma_password='+ str(self.win.Config[self.Title]['PASS'])
        except:
            traceback.print_exc()
            self.Login = ''
            

    def UpdateOption(self) :
        try :
            self.DEFOPTION = self.win.Config[self.Title]['DEFOPTION']
        except:
            traceback.print_exc()
            self.DEFOPTION = '0'


    def UpdateTimeout(self,timeout) :
        try :
            self.TIMEOUT    =   int(self.win.Config[self.Title]['TIMEOUT'])
        except:
            traceback.print_exc()
            self.TIMEOUT    =   timeout


    def LoginOk(self,Data)  :
        try :
            self.win.xPrint('--LoginOk')
            if ( reSearch('ma_password',Data) ) :
                self.win.xPrint('Login Error: Check Username/Password.')
                return False
            return True
        except:
            traceback.print_exc()
            return True


    def AddLogin(self,Url)  :
        try     :
            self.win.xPrint('--AddLogin')
            if self.Login !=    ''      :
                if '?' in str(Url)      :   Add     =   '&'
                else                    :   Add     =   '?'
                return str(Url) + str(Add) + str(self.Login)
            else                        :
                return str(Url)
        except:
            traceback.print_exc()
            self.win.xPrint('==AddLogin')
            return str(Url)
            

####################################################################################################################
######## START ###################### MAIN ######## ################################################################      
####################################################################################################################

    ##good
    def GetDownloads(self):
        self.win.xPrint('--GetDownloads')

        ## If its the first run then build Flag file and run the config first..
        FLAGFILE    =   str(self.win.Ctrl_) + str(self.Dir) +'\\first.run'
        if not (os.path.isfile(FLAGFILE))    :
            self.win.xPrint('** Config Needs to be run **')
            f = open(FLAGFILE,"wb")
            f.close()
            self.SystemMenu()
        
        Data        =   {}
        ## Run selection Based on Uploads,Downloads, Or Files..
        if      self.win.ViewState      ==  self.win.STATE_DOWN     :
            self.win.SiteLabel          =   'SabNZBd - Downloads ['+  str(self.win.Config[self.Title]['DNLABEL_']) +']'
            Data                        =   self.GetTorrents(self.win.Config[self.Title]['DNLABEL_'],self.DNLABEL_)

        elif    self.win.ViewState      ==  self.win.STATE_UP       :
            self.win.SiteLabel          =   'SabNZBd - History [ All Files ]'
            Data                        =   self.GetHistory()

        elif    self.win.ViewState      ==  self.win.STATE_FILES    :
            self.win.SiteLabel          =   'SabNZBd - File Listing ['+ str(self.TORRENT) +']'
            Data                        =   self.GetFiles()
        self.win.xPrint('++GetDownloads')
        return Data       


    ##good
    def GetTorrents(self,Label2,Extras) :
        try :
            self.win.xPrint('--GetTorrents')
            ## Initialise Variables that will be passed back ##
            Tor                     =   {}
            Tor_Array               =   []
            Queue                   =   0
            GlobalMsg               =   ''

            ## Process the Command..
            ActionUrx   =   str(self.FullUrl) + 'queue'
            ActionUrl   =   self.AddLogin(ActionUrx)
                
            Response    =   self.win.UrlThread(ActionUrl                                        ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response ==  None                :   raise Exception
            if not ( self.LoginOk(Response))    :   raise Exception
                
            Tar                     =   []         
            Exp     =   reCompile('<tr class=.*?'
                                  '<input type=\"hidden\" value=\"(.*?)\".*?>.*?'   ## ID
                                  '<td>(.*?)</td>.*?'                               ## Index No
                                  '<td>(.*?)</td>.*?'                               ## Download Option
                                  '<td>(.*?)</td>.*?'                               ## nzb Name
                                  '<td.*?>(.*?)</td>.*?'                            ## Left / Total
                                  '<td>(.*?)</td>.*?'                               ## ETA
                                  '<td>(.*?)</td>.*?'                               ## Time On Site
                                  '</tr>',reDotAll)

            Tar                         =   reFindall(Exp,Response)

            for _a in Tar   :
                Nm                      =   str(reSub('<.*?>','',_a[3][:-4]))
                Tor[Nm]                 =   {}
                Tor[Nm]['Id']           =   str(_a[0])
                Tor[Nm]['Index']        =   str(reFindall('selected>(\d+)</option>',_a[1])[0])
                Tmp                     =   reFindall('selected>[^<]',_a[2])
                if len(Tmp)             ==  1       :
                    Value               =   str(Tmp[0][-1:])
                    if    Value == 'R'  :
                        Tor[Nm]['Option']   =   'Repair'
                        Health              =   4   ## Green
                    elif  Value == 'U'  :
                        Tor[Nm]['Option']   =   'Unpack'
                        Health              =   2   ## Blue
                    elif  Value == 'D'  :
                        Tor[Nm]['Option']   =   'Delete'
                        Health              =   3   ## Yellow
                    else                :
                        Tor[Nm]['Option']   =   'None'
                        Health              =   1   ## Grey
                else                    :
                    Tor[Nm]['Option']   =   'None'
                    Health              =   1
                Suffix                  =   str(_a[4].split(' ')[-1])
                Size                    =   int(float(_a[4].split('/')[1][:-(len(Suffix)+1)]))
                Left                    =   int(float(_a[4].split('/')[0]))
                Tor[Nm]['Size']         =   str(Size) +' '+ str(Suffix)
                Tor[Nm]['Left']         =   str(Left) +' '+ str(Suffix)
                Tor[Nm]['Eta']          =   str(_a[5])
                Tor[Nm]['Time']         =   str(_a[6])

                ## If size to small dont report it..
                if Left < 1 or Size < 1     :
                    Pct                 =   'N/A '
                else                        :
                    Pct                     =   abs(((Left * 100) / Size) - 100)
                Tor[Nm]['CompPct']      =   str(Pct) +'%'
                Health_Img  =   self.win.MEDIA +'health-'+ str(Health) +'.png'

                ## Now Create Extra Information Tags to be displayed when focused.
                ExtraInf    =   ''
                for xtra in Extras  :
                    ExtraInf    +=   str(xtra)+':'+ str(Tor[Nm][str(xtra)])+ ' / '

                TORITEM     =   xListItem(str(Nm),Tor[Nm][Label2],ExtraInf,Health_Img)
                Tor_Array.append(TORITEM)
            
            ## Get the Summary Information
            GlobalMsg   =   self.Footer(Response)            

            self.win.xPrint('++GetTorrents')            
            return {'Torrents':Tor,'TorListItem':Tor_Array,'Queue':Queue,'GlobalMsg':GlobalMsg}         
        except:
            traceback.print_exc()
            self.win.xPrint('==GetTorrents')            
            return None

    
    ##good
    def GetHistory(self)    :
        try :
            self.win.xPrint('--GetHistory')
            ## Initialise Variables that will be passed back ##
            Tor                     =   {}
            Tor_Array               =   []
            Queue                   =   0
            GlobalMsg               =   ''

            ## Process the Command..
            ActionUrx   =   str(self.FullUrl) + 'history'
            ActionUrl   =   self.AddLogin(ActionUrx)

            Response    =   self.win.UrlThread(ActionUrl                                            ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response ==  None                :   raise Exception
            if not ( self.LoginOk(Response) )   :   raise Exception

            Tar                     =   []         
            Exp     =   reCompile('<tr class=\"(odd|even)\">'       ## Dummy
                                  '<td>(.*?)</td>'                  ## Date
                                  '<td>(.*?)</td>'                  ## NZB Name
                                  '<td>(.*?)</td></tr>'             ## True or False for LOADED
                                  ,reDotAll)

            Tar                         =   reFindall(Exp,Response)

            for _a in Tar   :
                Nm                      =   str(_a[2][:-4])
                Tor[Nm]                 =   {}
                Tor[Nm]['Date']         =   str(_a[1])
                if      str(_a[3])      == 'False'  :   Health  =   5
                elif    str(_a[3])      == 'True'   :   Health  =   4
                else                                :   Health  =   1
                self.win.xPrint(str(Tor[Nm]))
                Health_Img  =   self.win.MEDIA +'health-'+ str(Health) +'.png'
                TORITEM     =   xListItem(str(Nm),Tor[Nm]['Date'],'No Additional Info',Health_Img)
                Tor_Array.append(TORITEM)

            ## Get the Summary Information
            GlobalMsg   =   self.Footer(Response)            

            self.win.xPrint('++GetHistory')            
            return {'Torrents':Tor,'TorListItem':Tor_Array,'Queue':Queue,'GlobalMsg':GlobalMsg}         
        except:
            traceback.print_exc()
            self.win.xPrint('==GetHistory')            
            return None


    ##good
    def Footer(self,Response):
        try :
            self.win.xPrint('--Footer')
            Xp      =   reCompile('<div class=\"footer\">(.*?)</div>',reDotAll)            
            Ft      =   reFindall(Xp,Response)
            LabelTxt    =   ''
            if len(Ft)  ==  1   :
                if reSearch('<b>PAUSED</b>',Ft[0])  :   self.PAUSED =   True
                else                                :   self.PAUSED =   False
                Foot        =   Ft[0].split('b>')
                LabelTxt    +=  ' Speed : '     +   str(Foot[6][1:-4])
                if ( self.PAUSED )  :   LabelTxt    +=  ' Queued : '    +   str(Foot[8][1:-4]) + ' [PAUSED]' 
                else                :   LabelTxt    +=  ' Queued : '    +   str(Foot[8].rsplit(' ',1)[0][1:])

            self.win.xPrint('++Footer')
            return LabelTxt
        except :
            traceback.print_exc()
            self.win.xPrint('==Footer')
            return ''
            

    ##good
    def GetFiles(self) :
        try :
            self.win.xPrint('--GetFiles')
            ## Initialise Temp Variables
            Tor                     =   {}
            Tor_Array               =   []
            GlobalMsg               =   ''
            
            ## Process the Command..
            ActionUrx   =   str(self.FullUrl + 'queue/%s/') % str(self.FILEHASH)
            ActionUrl   =   self.AddLogin(ActionUrx)

            Response    =   self.win.UrlThread(ActionUrl                                                ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response ==  None                :   raise Exception
            if not ( self.LoginOk(Response) )   :   raise Exception

            Tar             =   []
            Exp             =   reCompile('<tr class=\"(oddLine|evenLine) active\">.*?'             ## 0 odd/even
                                          '<td><input type=\"checkbox\" name=\"(.*?)\" ></td>.*?'   ## Idx
                                          '<td>(.*?)</td>.*?'                                       ## Article Name
                                          '<td>(.*?)</td>.*?'                                       ## Size
                                          '<td>(.*?)</td>.*?'
                                          '</tr>',reDotAll)
            Tar             =   reFindall(Exp,Response)
            
            if len(Tar) >= 1 :
                for _a in Tar           :
                    Nm                  =   str(_a[2])
                    Tor[Nm]             =   {}
                    Tor[Nm]['Size']     =   str(_a[3])
                    Tor[Nm]['Idx']      =   str(_a[1])
                    Health              =   4
                    Health_Img          =   self.win.MEDIA +'health-'+ str(Health) +'.png'
                    TORITEM             =   xListItem(str(Nm),str(Tor[Nm]['Size']),'No Additional Info',Health_Img)
                    Tor_Array.append(TORITEM)
                    
            ## Get the Summary Information
            GlobalMsg   =   self.TORRENT

            self.win.xPrint('++GetFiles')            
            return {'Torrents':Tor,'TorListItem':Tor_Array,'GlobalMsg':GlobalMsg}         
        except:
            traceback.print_exc()
            self.win.xPrint('==GetFiles')            
            return None


####################################################################################################################
######## START ###################### TORRENT/FILE ACTIONS #########################################################      
####################################################################################################################


    ##good
    def KeyAction(self,Buttons,Labels):
        try :
            self.win.xPrint('--KeyAction: '+ str(Labels) +'-'+ str(Buttons))
            Action      =   Buttons[2]           
            Options     =   []
            
            ## moveUp/Down for selected Torrent
            if      Action[:4] ==  'move'      :
                Rec             =   self.win.Torrents[Labels[0]]
                SwitchRec       =   -1

                if   Action     ==  'moveup'    :
                    if int(Rec['Index']) !=  0                      :
                        SwitchRec =   int(Rec['Index'])   -   1
                elif Action     ==  'movedown'  :
                    if int(Rec['Index']) <  len(self.win.Torrents)  :
                        SwitchRec =   int(Rec['Index'])   +   1
                        
                if SwitchRec    !=  -1  :
                    for Key in self.win.Torrents.keys():
                        if int(self.win.Torrents[Key]['Index'])  ==  SwitchRec :
                            SwitchId    =   self.win.Torrents[Key]['Id']

                    if SwitchId != ''   :
                        ActionUrx   =   str(self.FullUrl) +'queue/switch?uid1='+ str(Rec['Id']) +'&uid2='+ str(SwitchId)
                        ActionUrl   =   self.AddLogin(ActionUrx)

                        Response    =   self.win.UrlThread(ActionUrl                                        ,   \
                                                           timeout=int(self.win.Config[self.Title]['TIMEOUT']))
                        if Response ==  None    :   raise Exception
                        else                    :   return True,True
                return True,False
                
            ## PurgeHistory.
            elif    Action      ==  'purgehistory'  :
                ActionUrx   =   str(self.FullUrl) +'history/purge'
                ActionUrl   =   self.AddLogin(ActionUrx)

                Response    =   self.win.UrlThread(ActionUrl                                        ,   \
                                                   timeout=int(self.win.Config[self.Title]['TIMEOUT']))
                if Response ==  None    :   raise Exception
                else                    :   return True,True                   
                
            ## Display Menu additional Options
            elif    Action      ==  'torrentmenu'   :
                Result = self.TorrentMenu(Labels[0])
                if ( Result )   :   return True,True
                else            :   return False,False

            ## Global Configuration Options
            elif    Action      ==  'configmenu'    :
                Result = self.ConfigMenu()
                if ( Result )   :   return True,True
                else            :   return False,False

            ## System Options
            elif    Action      ==  'systemmenu'    :
                self.SystemMenu()
                return True,False

            ## Set as Default
            elif    Action      ==  'setdefault'    :
                self.win.SetDefault(self.Title)
                return True,False

            ## Switch to Files View for the Torrent
            elif    Action      == 'showfiles'      :
                self.ViewState      =   self.win.ViewState
                self.win.ViewState  =   self.win.STATE_FILES
                self.FILEHASH       =   str(self.win.Torrents[Labels[0]]['Id'])
                self.TORRENT        =   str(Labels[0])
                return True,True

            ## Switch to Torrents View.
            elif    Action      ==  'shownzbs'      :
                self.win.ViewState  =   self.ViewState
                self.FILEHASH   =   ''
                self.TORRENT    =   ''
                return True,True
                
            ## Nothing To Do..
            self.win.xPrint('Cant Find anything to do.')
            self.win.xPrint('++KeyAction')
            return True,False
        except :
            traceback.print_exc()    
            self.win.UpdateProgress(self._[31],-1)
            self.win.xPrint('==KeyAction')
            return False,False


    ##good
    def TorrentMenu(self,Label): 
        try :
            self.win.xPrint('--Torrent Menu')

            ## Available Local Options:
            Options     =   []
            Rec         =   self.win.Torrents[Label]
            if ( self.PAUSED )  :   Options.append(['Resume Downloads','queue/resume',''])
            else                :   Options.append(['Pause Downloads' ,'queue/pause',''])
            Changes             =   {'None':'0','+Repair':'1','+Unpack':'2','+Delete':'3'}
            for Key in Changes.keys()   :
                if Key  !=  Rec['Option']   :
                    URL     =   'queue/change_opts?nzo_id='+ str(Rec['Id']) +'&pp='
                    Options.append(['Set Mode ('+ str(Key) +')',URL + str(Changes[Key]),''])
            Options.append(['Delete','queue/delete?uid='+ str(Rec['Id']),''])                          

            ## Display Menu:
            MenuList = []
            for List in Options:    MenuList.append(List[0])
            Answer = self.win.Menu.select(self._[14],MenuList)

            ## Process Answer
            if Answer != -1 :
                if      'delete'    in  Options[Answer][1]  :
                    YesNo = self.win.Menu.yesno(self._[17],self._[18],Label)
                    if not YesNo    :   self.win.xPrint('Dont do it!')
                            
                ## Process the Command..
                ActionUrx   =   str(self.FullUrl) + str(Options[Answer][1]) 
                ActionUrl   =   self.AddLogin(ActionUrx)
                
                Response    =   self.win.UrlThread(ActionUrl                                        ,   \
                                                   timeout=int(self.win.Config[self.Title]['TIMEOUT']))
                if Response ==  None    :   raise Exception
                else                    :   return True

            self.win.xPrint('Nothing to update')
            self.win.xPrint('==Torrent Menu')
            return True
        except:
            traceback.print_exc()
            self.win.xPrint('==Torrent Menu')
            return False


    ##working on
    def ConfigMenu(self):
        try :
            self.win.xPrint('--ConfigMenu')
            OK = False
            while not ( OK )    :            
                ## Available Configurations for Controller..
                ## 0 =  Display Name,   1 = Variable Name,  2 = Variable Type.
                ArrOpt  =   ['0' ,'1' ,'2'  ,'3']
                ArrTxt  =   ['None' ,'+Repair'  ,'+Unpack'  ,'+Delete'  ]
                TMPDEF  =   ArrOpt.index(str(self.win.Config[self.Title]['DEFOPTION']))

                Config      =   [['Default Option ['+ str(ArrTxt[TMPDEF])                           +']' ,'DEFOPTION','SUB'] , \
                                 ['**** DONE ****'  ,'OK','OK']]


                ## Display Menu.
                MenuList            =   []
                for List in Config  :
                    MenuList.append(List[0])
                Answer = self.win.Menu.select(self._[14],MenuList)

                ## Now work on the Results.
                if Answer != -1         :
                    Result  =   -1
                    if      Config[Answer][2]   ==  'IP'    :
                        Result  =   self.win.Menu.numeric(3,str(MenuList[Answer]) +': ['+ \
                                                          str(self.win.Config[self.Title][Config[Answer][1]]) +']')

                    elif    Config[Answer][2]   ==  'INT'   :
                        Result  =   self.win.Menu.numeric(0,str(MenuList[Answer]) +': ['+ \
                                                          str(self.win.Config[self.Title][Config[Answer][1]]) +']')

                    elif    Config[Answer][2]   ==  'TXT'   :
                        Result  =   self.win.KeyText(str(self.win.Config[self.Title][Config[Answer][1]]),str(MenuList[Answer]))

                    elif    Config[Answer][2]   ==  'SUB'   :
                        self.win.xPrint('--Pos:'+ str(TMPDEF))
                        if      TMPDEF + 1  ==  len(ArrOpt)     :   Result   =   str(ArrOpt[0])
                        else                                    :   Result   =   str(ArrOpt[TMPDEF + 1])                

                    elif    Config[Answer][2]   ==  'OK'   :
                        OK = True
                        
                    if Result == -1 or Result == '' :
                        self.win.xPrint('-1 or empty return so dont update it..')
                    else                            :
                        ## Clear the Cookie, Reset the Variables and Update config item..
                        #core.ClearCookie(str(self.win.Config[self.Title]['IP']))
                        self.win.Config[self.Title][Config[Answer][1]] = str(Result)
                        self.ClearVars()
                        self.UpdateAll()
                        self.win.ResetVars()
                else                    :
                    OK = True
            self.win.xPrint('++ConfigMenu')
        except:
            traceback.print_exc()
            self.win.xPrint('==ConfigMenu')


    ##working on
    def SystemMenu(self):
        try :
            self.win.xPrint('--SystemMenu')
            OK = False
            while not ( OK )    :            
                ## Available Configurations for Controller..
                Config      =   [['IP Address ['    + str(self.win.Config[self.Title]['IP'])        +']' ,'IP'       ,'IP']  , \
                                 ['Timeout ['       + str(self.win.Config[self.Title]['TIMEOUT'])   +']' ,'TIMEOUT'  ,'INT'] , \
                                 ['PORT Number ['   + str(self.win.Config[self.Title]['PORT'])      +']' ,'PORT'     ,'INT'] , \
                                 ['Username ['      + str(self.win.Config[self.Title]['USER'])      +']' ,'USER'     ,'TXT'] , \
                                 ['Password ['      + str(self.win.Config[self.Title]['PASS'])      +']' ,'PASS'     ,'TXT'] , \
                                 ['**** DONE ****'  ,'OK','OK']]

                ## Display Menu.
                MenuList            =   []
                for List in Config  :
                    MenuList.append(List[0])
                Answer = self.win.Menu.select(self._[14],MenuList)

                ## Now work on the Results.
                if Answer != -1         :
                    Result  =   -1
                    if      Config[Answer][2]   ==  'IP'    :
                        Result  =   self.win.Menu.numeric(3,str(MenuList[Answer]) +': ['+ \
                                                          str(self.win.Config[self.Title][Config[Answer][1]]) +']')

                    elif    Config[Answer][2]   ==  'INT'   :
                        Result  =   self.win.Menu.numeric(0,str(MenuList[Answer]) +': ['+ \
                                                          str(self.win.Config[self.Title][Config[Answer][1]]) +']')

                    elif    Config[Answer][2]   ==  'TXT'   :
                        Result  =   self.win.KeyText(str(self.win.Config[self.Title][Config[Answer][1]]),str(MenuList[Answer]))

                    elif    Config[Answer][2]   ==  'OK'   :
                        OK = True
                        
                    if Result == -1 or Result == '' :
                        self.win.xPrint('-1 or empty return so dont update it..')
                    else                            :
                        ## Clear the Cookie, Reset the Variables and Update config item..
                        #core.ClearCookie(str(self.win.Config[self.Title]['IP']))
                        self.win.Config[self.Title][Config[Answer][1]] = str(Result)
                        self.ClearVars()
                        self.UpdateAll()
                        self.win.ResetVars()
                else                    :
                    OK = True
            self.win.xPrint('++SystemMenu')
        except:
            traceback.print_exc()
            self.win.xPrint('==SystemMenu')

####################################################################################################################
######## START ###################### TORRENTS ADDED AND LISTED ####################################################      
####################################################################################################################

    def SendTorrent(self,LookDir,TorrentFile)   :
        try     :
            self.win.xPrint('--SendTorrent')
            ## Read file data..
            realfile        =   LookDir + TorrentFile
            f               =   open(realfile,'r')
            fdata           =   f.read()
            f.close()

            ## Create post data..                        
            Contentx,Postx      =   self.win.MultiPart([['pp',str(self.DEFOPTION)]]                             ,   \
                                                       [['nzbfile',TorrentFile,str(fdata)]],'nzb')

            ## Now Action the command..
            ActionUrx   =   str(self.FullUrl)    +   'addFile' 
            ActionUrl   =   self.AddLogin(ActionUrx)

            Response            =   self.win.UrlThread(ActionUrl                                                ,   \
                                                       post=Postx                                               ,   \
                                                       timeout=int(self.win.Config[self.Title]['TIMEOUT'])      ,   \
                                                       xContent=Contentx)
            if Response ==  None    :   raise Exception
            else                    :   return True
            self.win.xPrint('++SendTorrent')
        except  :
            traceback.print_exc()
            self.win.xPrint('==SendTorrent')
            return False
